<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { RefreshRight } from '@element-plus/icons-vue'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer'
import Graphic from '@arcgis/core/Graphic'

// 状态变量
const loading = ref(false)
const maintenanceBikes = ref<any[]>([])
const selectedBike = ref<any>(null)
const showMaintenanceDialog = ref(false)
const showSuccessDialog = ref(false)
const successMessage = ref('')
const filterStatus = ref('')

// 维修表单
const maintenanceForm = ref({
  maintenanceStatus: '',
  maintenanceReason: '',
})

// 自行车图层
let bikeLayer: FeatureLayer | null = null

// 初始化
onMounted(() => {
  initBikeLayer()
  loadMaintenanceBikes()
})

// 初始化自行车图层
const initBikeLayer = () => {
  bikeLayer = new FeatureLayer({
    url: 'https://services7.arcgis.com/rDRhdC4brwj3FLD5/arcgis/rest/services/cycleFeaturelayer/FeatureServer/0',
    outFields: ['*'],
  })
}

// 加载维修中的单车
const loadMaintenanceBikes = async () => {
  if (!bikeLayer) return

  loading.value = true
  try {
    // 查询维修中的单车
    const query = bikeLayer.createQuery()
    let whereClause = "Status = '维修中'"

    // 根据维修状态过滤
    if (filterStatus.value) {
      whereClause += ` AND MaintenanceStatus = '${filterStatus.value}'`
    }

    query.where = whereClause
    query.outFields = ['*']
    query.returnGeometry = true

    const results = await bikeLayer.queryFeatures(query)
    maintenanceBikes.value = results.features.map((feature) => ({
      ...feature.attributes,
      geometry: feature.geometry,
    }))
  } catch (error) {
    console.error('加载维修单车失败:', error)
    ElMessage.error('加载维修单车失败')
  } finally {
    loading.value = false
  }
}

// 打开维修对话框
const openMaintenanceDialog = (bike: any) => {
  selectedBike.value = bike
  maintenanceForm.value.maintenanceStatus = bike.MaintenanceStatus || '等待维修'
  maintenanceForm.value.maintenanceReason = bike.MaintenanceReason || ''
  showMaintenanceDialog.value = true
}

// 更新维修状态
const updateMaintenanceStatus = async () => {
  if (!bikeLayer || !selectedBike.value) {
    ElMessage.error('单车信息不完整')
    return
  }

  if (!maintenanceForm.value.maintenanceStatus) {
    ElMessage.warning('请选择维修状态')
    return
  }

  try {
    loading.value = true
    const bike = selectedBike.value

    // 准备更新的属性
    const attributes: any = {
      OBJECTID: bike.OBJECTID,
      MaintenanceStatus: maintenanceForm.value.maintenanceStatus,
    }

    // 如果维修原因发生变化，也更新
    if (maintenanceForm.value.maintenanceReason !== bike.MaintenanceReason) {
      attributes.MaintenanceReason = maintenanceForm.value.maintenanceReason
    }

    // 如果维修完成，更新单车状态为可用
    if (maintenanceForm.value.maintenanceStatus === '维修完成') {
      attributes.Status = '可用'
      attributes.MaintenanceStatus = ''
      attributes.MaintenanceReason = ''
    }

    // 创建更新要素（不包含几何信息）
    const updateFeature = new Graphic({
      attributes: attributes
    })

    // 更新要素
    const results = await bikeLayer.applyEdits({
      updateFeatures: [updateFeature],
    })

    if (results.updateFeatureResults && results.updateFeatureResults.length > 0) {
      // 关闭维修对话框
      showMaintenanceDialog.value = false

      // 显示成功信息
      let statusText = maintenanceForm.value.maintenanceStatus === '维修完成' ? '已完成维修并恢复可用状态' : `已更新为「${maintenanceForm.value.maintenanceStatus}」状态`
      successMessage.value = `单车维修状态更新成功！\n单车ID: ${bike.BikeId}\n${statusText}`
      showSuccessDialog.value = true

      // 刷新维修列表
      loadMaintenanceBikes()
    } else {
      ElMessage.error('更新维修状态失败')
    }
  } catch (error) {
    console.error('更新维修状态时出错:', error)
    ElMessage.error('操作失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 关闭成功对话框
const closeSuccessDialog = () => {
  showSuccessDialog.value = false
}

// 刷新列表
const refreshList = () => {
  loadMaintenanceBikes()
}
</script>

<template>
  <div class="admin-maintenance">
    <el-card class="maintenance-card">
      <template #header>
        <div class="card-header">
          <h2>维修管理</h2>
          <div class="header-actions">
            <el-select
              v-model="filterStatus"
              placeholder="按维修状态筛选"
              clearable
              @change="loadMaintenanceBikes"
              style="width: 150px"
            >
              <el-option label="等待维修" value="等待维修"></el-option>
              <el-option label="维修中" value="维修中"></el-option>
              <el-option label="维修完成" value="维修完成"></el-option>
            </el-select>
            <el-button type="primary" @click="refreshList" :icon="RefreshRight">刷新</el-button>
          </div>
        </div>
      </template>

      <el-alert
        title="维修管理页面显示所有需要维修的单车，点击单车卡片可以更新维修状态"
        type="info"
        :closable="false"
        show-icon
        class="info-alert"
      />

      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>

      <el-empty
        v-else-if="maintenanceBikes.length === 0"
        description="没有需要维修的单车"
      >
        <template #image>
          <el-icon class="empty-icon"><svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
            <path fill="currentColor" d="M512 896a384 384 0 1 0 0-768 384 384 0 0 0 0 768zm0 64a448 448 0 1 1 0-896 448 448 0 0 1 0 896z"></path>
            <path fill="currentColor" d="M480 256a32 32 0 0 1 32 32v256a32 32 0 0 1-64 0V288a32 32 0 0 1 32-32z"></path>
            <path fill="currentColor" d="M480 512h256a32 32 0 0 1 0 64H480a32 32 0 0 1 0-64z"></path>
          </svg></el-icon>
        </template>
      </el-empty>

      <div v-else class="maintenance-list">
        <el-card
          v-for="bike in maintenanceBikes"
          :key="bike.BikeId"
          class="bike-item"
          @click="openMaintenanceDialog(bike)"
        >
          <div class="bike-info">
            <div class="bike-header">
              <span class="bike-type">{{ bike.BikeType }}</span>
              <el-tag size="small" type="danger">ID: {{ bike.BikeId }}</el-tag>
            </div>

            <div class="bike-details">
              <p><strong>当前地址:</strong> {{ bike.NowAddress }}</p>
              <p>
                <strong>维修状态:</strong>
                <el-tag
                  :type="bike.MaintenanceStatus === '等待维修' ? 'warning' :
                         bike.MaintenanceStatus === '维修中' ? 'primary' : 'success'"
                  size="small"
                >
                  {{ bike.MaintenanceStatus || '等待维修' }}
                </el-tag>
              </p>
              <p><strong>故障原因:</strong> {{ bike.MaintenanceReason }}</p>
              <p v-if="bike.BikeType === '电动单车'"><strong>电量:</strong> {{ bike.BatteryLevel }}</p>
            </div>

            <div class="bike-actions">
              <el-button type="primary" size="small" @click.stop="openMaintenanceDialog(bike)">
                <el-icon class="el-icon--left"><svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
                  <path fill="currentColor" d="M600.704 64a32 32 0 0 1 30.464 22.208l35.2 109.376c14.784 7.36 28.928 15.872 42.432 25.504l110.336-32.064a32 32 0 0 1 34.432 15.36L944.32 364.8a32 32 0 0 1-4.032 38.016l-80.896 79.872c.576 17.408.576 34.848 0 52.224l80.896 79.872a32 32 0 0 1 4.032 38.016l-91.328 158.08a32 32 0 0 1-34.432 15.424l-109.824-32.064c-13.44 9.664-27.648 18.176-42.368 25.536l-35.264 109.312a32 32 0 0 1-30.464 22.208H483.008a32 32 0 0 1-30.464-22.208l-35.2-109.312c-14.72-7.36-28.928-15.872-42.432-25.536l-110.336 32.064a32 32 0 0 1-34.432-15.424l-91.328-158.08a32 32 0 0 1 4.032-38.016l80.896-79.872a352.8 352.8 0 0 1 0-52.224l-80.896-79.872a32 32 0 0 1-4.032-38.016l91.328-158.08a32 32 0 0 1 34.432-15.424l109.824 32.064c13.44-9.664 27.648-18.176 42.368-25.504l35.264-109.376A32 32 0 0 1 483.008 64h117.696zm-32.64 384v96a32 32 0 0 1-32 32h-96a32 32 0 0 1-32-32v-96a32 32 0 0 1 32-32h96a32 32 0 0 1 32 32z"></path>
                </svg></el-icon>
                更新状态
              </el-button>
            </div>
          </div>
        </el-card>
      </div>
    </el-card>

    <!-- 维修状态更新对话框 -->
    <el-dialog
      v-model="showMaintenanceDialog"
      title="更新维修状态"
      width="500px"
      destroy-on-close
    >
      <el-form :model="maintenanceForm" label-position="top">
        <el-form-item label="单车信息">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="单车ID">{{ selectedBike?.BikeId }}</el-descriptions-item>
            <el-descriptions-item label="单车类型">{{ selectedBike?.BikeType }}</el-descriptions-item>
            <el-descriptions-item label="当前地址">{{ selectedBike?.NowAddress }}</el-descriptions-item>
          </el-descriptions>
        </el-form-item>

        <el-form-item label="维修状态" required>
          <el-select v-model="maintenanceForm.maintenanceStatus" placeholder="请选择维修状态" style="width: 100%">
            <el-option label="等待维修" value="等待维修"></el-option>
            <el-option label="维修中" value="维修中"></el-option>
            <el-option label="维修完成" value="维修完成"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="故障原因">
          <el-input
            v-model="maintenanceForm.maintenanceReason"
            type="textarea"
            :rows="4"
            placeholder="故障原因描述"
          ></el-input>
        </el-form-item>

        <el-alert
          v-if="maintenanceForm.maintenanceStatus === '维修完成'"
          title="注意：选择“维修完成”将自动将单车状态更新为“可用”"
          type="warning"
          :closable="false"
          show-icon
        />
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showMaintenanceDialog = false">取消</el-button>
          <el-button type="primary" @click="updateMaintenanceStatus" :loading="loading">更新状态</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 操作成功提示对话框 -->
    <el-dialog
      v-model="showSuccessDialog"
      title="更新成功"
      width="30%"
      center
    >
      <div class="success-content">
        <el-icon class="success-icon" size="large" color="#67C23A">
          <svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
            <path
              fill="currentColor"
              d="M512 64a448 448 0 1 1 0 896 448 448 0 0 1 0-896zm-55.808 536.384-99.52-99.584a38.4 38.4 0 1 0-54.336 54.336l126.72 126.72a38.272 38.272 0 0 0 54.336 0l262.4-262.464a38.4 38.4 0 1 0-54.272-54.336L456.192 600.384z"
            />
          </svg>
        </el-icon>
        <p class="success-message">{{ successMessage }}</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="closeSuccessDialog">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.admin-maintenance {
  padding: 20px;
}

.maintenance-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.card-header h2 {
  margin: 0;
  font-size: 20px;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.info-alert {
  margin-bottom: 20px;
}

.loading-container {
  padding: 20px 0;
}

.maintenance-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
  margin-top: 16px;
}

.bike-item {
  border-radius: 8px;
  transition: all 0.3s;
  cursor: pointer;
}

.bike-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
}

.bike-info {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.bike-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.bike-type {
  font-weight: bold;
  font-size: 16px;
  color: #303133;
}

.bike-details {
  font-size: 14px;
  color: #606266;
}

.bike-details p {
  margin: 5px 0;
}

.bike-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 8px;
}

.empty-icon {
  font-size: 60px;
  color: #909399;
}

.success-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0;
}

.success-icon {
  font-size: 60px;
  margin-bottom: 20px;
}

.success-message {
  text-align: center;
  white-space: pre-line;
  color: #606266;
}
</style>
